<template>
    <yh-dialog
        :visible.sync="visibleTemp"
        v-bind="$attrs"
        title="事件处理"
        :modal="false"
        :close-on-click-modal="false"
        drag
        zoomable
        width="60vw"
        @close="handleCloseDialog"
        top="10vh"
    >
        <div :class="{ 'follow-manage': type === 'follow-manage', 'dialog-main': true }">
            <!-- 新增和查看的区分 -->
            <div class="table" v-if="type != 'follow-manage'">
                <el-row>
                    <el-col :span="5">事件编号</el-col>
                    <el-col :span="7">
                        <el-input v-model="submitForm.overrunEventId" disabled size="mini"></el-input>
                    </el-col>
                    <el-col :span="5">产品代码/名称</el-col>
                    <el-col :span="7">
                        <span v-if="isLook">
                            {{ formatDictFundCodes(submitForm.dictFundCodes) }}
                        </span>
                        <el-select
                            v-model="submitForm.fundProductCode"
                            filterable
                            multiple
                            collapse-tags
                            clearable
                            size="mini"
                            v-else
                            @change="paramsChange('fundCode', $event)"
                        >
                            <el-option
                                v-for="i in computedFundStorage"
                                :key="i.fundCode"
                                :label="i.fundProductCode + ' ' + i.fundName"
                                :value="i.fundCode"
                            >
                            </el-option>
                        </el-select>
                        <!-- <RiskEntryInputs
                            @set-entry-data="val => (submitForm.fundProductCode = val)"
                            :showDis="false"
                            :showAll="false"
                            :returnDatas="submitForm.fundProductCode"
                            dictKey="fundProductCode"
                            :disabled="type == 'look'"
                            style="width:100%"
                        /> -->
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="5">估值日期</el-col>
                    <el-col :span="7">
                        <!-- {{ submitForm.tradeDate }} -->
                        <el-date-picker
                            v-model="submitForm.tradeDate"
                            type="date"
                            size="mini"
                            style="width: 100%"
                            value-format="yyyyMMdd"
                            format="yyyy-MM-dd"
                            :disabled="isLook"
                            @change="paramsChange('tradeDate', $event)"
                        >
                        </el-date-picker>
                    </el-col>
                    <el-col :span="5">投资经理</el-col>
                    <el-col :span="7">
                        <!-- {{ submitForm.investmentManager }} -->
                        <el-input v-model="submitForm.investmentManager" disabled clearable size="mini"></el-input>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="5">指标说明</el-col>
                    <el-col :span="7">
                        <!-- {{ submitForm.entryName }} -->
                        <el-input v-model="submitForm.entryName" :disabled="isLook" clearable size="mini"></el-input>
                    </el-col>
                    <el-col :span="5">连续超限天数</el-col>
                    <el-col :span="7">
                        <!-- 当前日期-选择的估值日期 -->
                        <!-- {{ submitForm.prohibitionDate }} -->
                        <el-input v-model="submitForm.prohibitionDate" :disabled="isLook" clearable size="mini"></el-input>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="5">最后调整日期</el-col>
                    <el-col :span="7">
                        <!-- {{ submitForm.lastAdjustDate  }} -->
                        <el-date-picker
                            v-model="submitForm.lastAdjustDate"
                            type="date"
                            size="mini"
                            style="width: 100%"
                            value-format="yyyyMMdd"
                            format="yyyy-MM-dd"
                            :disabled="isLook"
                        >
                        </el-date-picker>
                    </el-col>
                    <el-col :span="5">控制阈值</el-col>
                    <el-col :span="7">
                        <el-input v-model="submitForm.thresholdValue" type="number" :disabled="isLook" clearable size="mini"></el-input>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="5">控制方向</el-col>
                    <el-col :span="7">
                        <!-- 默认大于 -->
                        <el-select v-model="submitForm.compareType" :disabled="isLook" clearable size="mini">
                            <el-option v-for="(value, key) in compareTypePojo" :key="key" :value="key" :label="value"> </el-option>
                        </el-select>
                    </el-col>
                    <el-col :span="5">指标状态</el-col>
                    <el-col :span="7">
                        <el-select v-model="submitForm.triggerType" disabled filterable clearable size="mini">
                            <el-option v-for="(value, key) in triggerTypePojo" :key="key" :value="key" :label="value"> </el-option>
                        </el-select>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="5">计算值</el-col>
                    <el-col :span="7">
                        <!-- 是否有非数字要求 TODO  -->
                        <el-input v-model="submitForm.result" :disabled="isLook" type="number" clearable size="mini"></el-input>
                    </el-col>
                    <el-col :span="5"> 发起日期 </el-col>
                    <el-col :span="7">
                        <el-date-picker
                            v-model="submitForm.approveDate"
                            type="date"
                            size="mini"
                            style="width: 100%"
                            value-format="yyyyMMdd"
                            format="yyyy-MM-dd"
                            disabled
                        >
                        </el-date-picker>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="5">事件来源</el-col>
                    <el-col :span="19">
                        <!-- {{ submitForm.articeInfo }} -->
                        <el-input v-model="submitForm.articeInfo" :disabled="isLook" clearable size="mini"></el-input>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="5"> 事件说明 </el-col>
                    <el-col :span="19">
                        <!-- {{ submitForm.clauseCode }}  -->
                        <el-input v-model="submitForm.clauseCode" :disabled="isLook" clearable size="mini"></el-input>
                    </el-col>
                </el-row>
                <!-- TODO -->
            </div>

            <!-- 跟踪管理 -->
            <div class="table" v-else>
                <el-row>
                    <el-col :span="5">估值日期</el-col>
                    <el-col :span="7">
                        <el-date-picker
                            v-model="submitFormFollow.tradeDate"
                            type="date"
                            size="mini"
                            style="width: 100%"
                            value-format="yyyyMMdd"
                            format="yyyy-MM-dd"
                        >
                        </el-date-picker>
                    </el-col>
                    <el-col :span="5">当前计算值</el-col>
                    <el-col :span="7">
                        <el-input v-model="submitFormFollow.result" clearable size="mini"></el-input>
                    </el-col>
                </el-row>
                <el-row class="textarea">
                    <el-col :span="5"> 记录填写: </el-col>
                    <el-col :span="19">
                        <el-input v-model="submitFormFollow.feedBackName" type="textarea" :rows="3" placeholder="填写记录数据或者描述"> </el-input>
                    </el-col>
                </el-row>
            </div>
            <div class="file-part" v-if="!isLook">
                <!-- 查看附件  TODO -->
                <el-upload
                    :multiple="true"
                    :action="actionUrl"
                    :headers="headerObj"
                    :with-credentials="true"
                    :before-upload="beforeAvatarUpload"
                    list-type="text"
                    :show-file-list="false"
                    :disabled="type === 'look'"
                    :on-success="
                        (res, file, fileList) => {
                            return uploadFileSuccess(res, file, fileList, '执行标准');
                        }
                    "
                    :on-error="
                        (res, file, fileList) => {
                            return uploadFileError(res, file, fileList, '执行标准');
                        }
                    "
                >
                    <i class="el-icon-plus" :disabled="type === 'look'" size="small"></i>
                </el-upload>
                <div class="text-file">添加附件</div>
            </div>
        </div>
        <UploadFileShow :fileList="fileList1" :type="type" @emitDownLoadFile="downLoadFileBtn" @emitConfirmDelFile="confirmDelFile1"></UploadFileShow>

        <div v-if="isLook || isFollow">
            <p class="title">历史记录信息</p>
            <RiskTable
                ref="risk-table2"
                :tableData="tableData"
                :tableConfig="tableConfig"
                :column="columns"
                :paging="paging"
                v-loading="tableLoading"
                style="height: 290px"
                @page-change="getFeedbackList"
            >
                <template #fileName="{ row }">
                    <span v-for="(item, index) in row.fileName" :key="index" @click="handleCellFile(item, row.fileCode[index])">
                        <a href="javascript:;">{{ item }}</a>
                    </span>
                </template>
            </RiskTable>
        </div>

        <div slot="footer" class="dialog-footer">
            <el-button size="mini" @click="handleCloseDialog"> 取 消 </el-button>
            <el-button size="mini" type="primary" @click="handleSave" v-if="type != 'look'">保 存 </el-button>
        </div>
    </yh-dialog>
</template>
<script lang="ts">
import { downLoadFile } from '@/utils/request';
import { changeOptions, dateFormat, getConfigItem, numberFormat, timeFormat } from '@/utils/tools';
import { getUser } from '@/utils/user-util';
import { Component, Prop, PropSync, Vue, Watch } from 'vue-property-decorator';
import RiskTable from '@/common/components/risk-table-plus.vue';
import { ColumnVO, PageVO, TableConfigVO } from '@/common/vo';
import XEUtils from 'xe-utils';
import { ManualEventRepVO } from '../../vo/manual-processing';
import API from '../../api/manual-processing';
// 引用前台处置中心的附件列表
import UploadFileShow from '../../disposal-center/upload-file-show.vue';
import RiskEntryInputs from '@/common/components/risk-entry-inputs.vue';
import Dict from '../../dict/index';
import JSEncrypt from 'jsencrypt';
import { SGU_CACHE } from '@/utils/diction-const-util';
import moment from 'moment';
@Component({ name: 'ManualEventRecord', components: { RiskTable, UploadFileShow, RiskEntryInputs } })
export default class ManualEventRecord extends Vue {
    @PropSync('visible') syncVisible: boolean;
    @Prop() overrunDetail: any;
    @Prop() type: string; // add | look
    Dict = new Dict();
    compareTypePojo = Dict.compareTypePojo;
    triggerTypePojo = Dict.triggerTypePojo;
    public visibleTemp: boolean = false;
    actionUrl: string = ''; // 附件上传url
    headerObj = { Authentication: getUser().sessionId }; // 上传接口请求表头
    fileList1: any[] = []; // 文件夹

    tableLoading: boolean = false;
    tableData: any[] = [];
    tableConfig: TableConfigVO = {
        rowKey: 'feedBackId', // 主键key
        allRowKeys: [], // 所有页数据的key集合
    };
    tableColumns: ColumnVO[] = [
        {
            title: '记录时间',
            field: 'ctDate',
            minWidth: 200,
            render: (value, row) => dateFormat(value) + ' ' + timeFormat(row.ctTime),
            align: 'center',
        },
        {
            title: '估值日期',
            field: 'tradeDate',
            align: 'center',
            minWidth: 120,
            render: value => dateFormat(value) || '--',
        },
        {
            title: '计算值',
            field: 'result',
            align: 'center',
            minWidth: 100,
            render: value => numberFormat(value) || '--',
        },
        {
            title: '记录内容',
            field: 'feedBackName',
            notShowTooltip: false,
            minWidth: 160,
        },
        {
            title: '附件',
            field: 'fileName',
            notShowTooltip: false,
            minWidth: 300,
        },
    ];

    get columns() {
        // if (this.type == 'follow-manage') {
        //     this.tableColumns.push({
        //         title: '附件',
        //         field: 'fileName',
        //         notShowTooltip: false,
        //         minWidth: 300,
        //     });
        // }
        return this.tableColumns;
    }
    paging: PageVO = { pageSize: 25, currentPage: 1, total: 0 };

    submitForm: ManualEventRepVO = {
        overrunEventId: undefined,
        fundProductCode: [],
        thresholdValue: '',
        compareType: '0',
        result: 0,
        prohibitionDate: 0, // 默认计算 = 当前日期-选择的估值日期;当前日期=估值日期时，为1。
        entryName: '',
        lastAdjustDate: '',
        articeInfo: '',
        clauseCode: '',
        tradeDate: '',
        investmentManager: '',
        triggerType: '3',
        approveDate: XEUtils.toDateString(new Date(), 'yyyyMMdd'), // 取当前系统日期
    };

    submitFormFollow: { tradeDate: string; result: string; feedBackName: string } = {
        tradeDate: '',
        result: '',
        feedBackName: '',
    };

    rsaPassWord: any = null; // 加密
    fundStorage: any[] = [];

    get isLook() {
        return this.type == 'look';
    }

    get isFollow() {
        return this.type == 'follow-manage';
    }

    // 已选项前置
    get computedFundStorage() {
        let arr = changeOptions(this.submitForm.fundProductCode, this.fundStorage, 'fundCode');
        return arr;
    }
    async mounted() {
        const baseURL = getConfigItem('BASE_URL_API');
        this.actionUrl = baseURL + '/apiAssetFile/upload';
        if (this.type != 'add') {
            this.type != 'follow-manage' && this.getDetailList();
            this.getFeedbackList();
            var encryptor = new JSEncrypt(); // 创建加密对象实例
            // 之前ssl生成的公钥，复制的时候要小心不要有空格
            var pubKey =
                'MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDI1/pR72vGeQoQ8YxKVrDzV6RriOkNkW0UWw4JgXhH417lULhKMQWK3GeJW+Tg0kHlhpx4iQNxrEPlroCqZfylgPI+x0AohcnvkY52VGQGLnms2tMefBKdz2BHUAp7MdF7GsGtpiHWSZbEWk5onkB7pH8Q0KlNAB+7BoNTj9MOywIDAQAB';
            encryptor.setPublicKey(pubKey); // 设置公钥
            this.rsaPassWord = encryptor.encrypt('zszg@zgssfkxt'); // 对内容进行加密
        }
        this.fundStorage = await SGU_CACHE('FundInfoByUser', '/fundInfo/list/byUser/like', []);
    }

    @Watch('visible', { immediate: true, deep: true })
    onWatchVisible(value) {
        if (value !== this.visibleTemp) {
            this.visibleTemp = value;
        }
    }

    /**
     * 获取历史反馈记录
     */
    getFeedbackList(): void {
        const feedBackType = this.type == 'look' ? '2' : '1';
        API.feedbackQuery({ overrunEventId: this.overrunDetail.overrunEventId, paging: this.paging, feedBackType: 1 }).then((res: any) => {
            if (['look'] && res.list && res.list.length && this.paging.currentPage === 1) {
                let fileList = [];
                res.list[0].fileName &&
                    res.list[0].fileName.forEach((ele, index) => {
                        fileList.push({
                            name: ele,
                            url: '',
                            fileNo: res.list[0].fileCode[index],
                        });
                    });
                // this.fileList1 = fileList;
            }
            this.tableData = res.list;
            this.paging.total = res.total;
        });
    }

    /**
     * 获取表单信息
     */
    getDetailList(): void {
        API.labourDetail({ overrunEventId: this.overrunDetail.overrunEventId }).then((res: any) => {
            let data = JSON.parse(JSON.stringify(res));
            data.tradeDate = data.tradeDate ? String(data.tradeDate) : '';
            // data.valuationDate = dateFormat(res.valuationDate) || '--';
            // data.result = numberFormat(res.result, 2) || '--';
            // data.thresholdValue = numberFormat(res.thresholdValue, 2) || '--';
            // data.ctDate = dateFormat(res.ctDate) || '--';
            this.submitForm = data;
        });
    }

    /**
     * 保存事件
     */
    handleSave(): void {
        if (!this.verify()) return;
        const fileCode = this.fileList1.map(item => item.fileNo);
        const fileName = this.fileList1.map(item => item.name);
        let data;
        if (this.type == 'follow-manage') {
            data = {
                fileCode,
                fileName,
                ...this.submitFormFollow,
                overrunEventId: this.overrunDetail.overrunEventId,
            };
        } else {
            data = {
                feedBackPO: { fileCode, fileName, result: this.submitForm.result, tradeDate: this.submitForm.tradeDate },
                ...this.submitForm,
            };
        }

        this.$emit('initEventRecord', data);
    }

    /**
     * 关闭dialog事件
     */
    handleCloseDialog(): void {
        this.syncVisible = false;
    }

    /**
     * 校验字段
     */
    verify() {
        // 产品为必选项
        if (this.type == 'follow-manage') {
            if (!this.submitFormFollow.tradeDate) {
                this.yh_message_warn('估值日期不可为空!');
                return false;
            }
            if (!this.submitFormFollow.result.trim()) {
                this.yh_message_warn('计算值不可为空!');
                return false;
            }
        } else {
            // 新增录入
            if (this.submitForm.fundProductCode.length < 1) {
                this.yh_message_warn('产品不可为空!');
                return false;
            } else if (!this.submitForm.lastAdjustDate) {
                this.yh_message_warn('最后调整日期不可为空');
                return false;
            }
            if (!this.submitForm.tradeDate) {
                this.yh_message_warn('估值日期不可为空!');
                return false;
            }
            if (!this.submitForm.thresholdValue) {
                this.yh_message_warn('控制阈值不可为空!');
                return false;
            }
            if (!this.submitForm.result && this.submitForm.result !== 0) {
                this.yh_message_warn('计算值不可为空!');
                return false;
            }
        }
        return true;
    }

    /**
     * 附件单元格点击事件
     */
    handleCellFile(name, code): void {
        console.log('current:: fileCode:', code);
        downLoadFile({
            url: '/apiAssetFile/downLoad',
            method: 'post',
            data: { fileId: [code], fileName: name, passWord: this.rsaPassWord },
        });
    }

    // 文件上传
    uploadFileSuccess(res, file, fileList, type) {
        console.log(res, file, fileList, type);
        if (res.returnMsg && res.returnMsg !== 'SUCCESS') {
            this.$message.warning(res.returnMsg);
            return;
        }
        this.fileList1.push({
            name: res.data.fileName,
            url: res.data.relativePath,
            fileNo: res.data.fileId,
        });
    }

    // 下载文件
    downLoadFileBtn(param) {
        downLoadFile({
            url: '/apiAssetFile/downLoad',
            method: 'post',
            data: { fileId: [param.fileNo], fileName: param.name, passWord: this.rsaPassWord },
        });
    }

    // 删除已上传文件
    confirmDelFile1(param) {
        this.fileList1.forEach((item, index) => {
            if (item.fileNo == param.fileNo) {
                this.fileList1.splice(index, 1);
            }
        });
    }

    // 格式化产品代码
    private formatDictFundCodes(cellValue): string {
        let valueStr = XEUtils.map(cellValue, item => {
            if (item) {
                return item.dictKey + '(' + item.dictKeyName + ')';
            } else {
                return '--';
            }
        });
        return valueStr.toString();
    }

    /**
     * 字段改变
     */
    paramsChange(type: string, value: any) {
        if (type == 'fundCode') {
            // 产品改变->获取投资经理
            API.investManagerCollect({ fundCode: value }).then((res: any) => {
                this.submitForm.investmentManager = res;
            });
        } else if (type == 'tradeDate') {
            // 估值日期推算出连续超限天数  TODO
            let day = moment(new Date()).diff(moment(this.submitForm.tradeDate), 'days') || 1; // 1
            this.submitForm.prohibitionDate = day;
            // console.log(this.submitForm.prohibitionDate, 'this.submitForm.prohibitionDate');
        }
    }

    beforeAvatarUpload(file) {
        // const isJPG = file.type === 'image/jpeg';
        const isLt2M = file.size / 1024 / 1024 < 10;

        // if (!isJPG) {
        //     this.$message.error('上传头像图片只能是 JPG 格式!');
        // }
        if (!isLt2M) {
            this.yh_message_warn('上传大小不能超过 10MB!');
        }
        return isLt2M;
    }
}
</script>
<style lang="scss" scoped>
.table {
    border-top: 1px solid rgba(239, 239, 239, 1);
    .el-row {
        border-right: 1px solid rgba(239, 239, 239, 1);
        display: flex;
        .el-col {
            border: 1px solid rgba(239, 239, 239, 1);
            border-top: none;
            border-right: none;
            padding: 5px 5px;
            min-height: 32px;
            font-size: 12px;
            display: flex;
            align-items: center;
        }
        .el-col-5 {
            justify-content: center;
            background: #f7f8fc;
        }
        .el-col-7,
        .el-col-19 {
            padding-left: 10px;
        }
    }

    .textarea {
        .el-col {
            min-height: 85px;
        }
        .el-col-5 {
            flex-direction: column;
        }
    }
}
.title {
    margin: 15px 10px 10px 0;
    display: flex;
    align-items: center;
    font-weight: 600;
}

// .title::before {
//     display: inline-block;
//     content: '';
//     width: 2px;
//     height: 20px;
//     background: #409eff;
//     margin-right: 10px;
// }

/* 附件链接 */
/deep/ .vxe-table .vxe-body--column .vxe-cell {
    height: auto;
    line-height: inherit;
}
/deep/ .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
}
.el-icon-plus {
    font-size: 28px;
    color: #8c939d;
    width: 80px;
    height: 80px;
    line-height: 80px;
    text-align: center;
}

.file-part {
    margin-top: 10px;
    .text-file {
        width: 80px;
        text-align: center;
    }
}

.follow-manage {
    display: flex;
    align-items: end;
    column-gap: 10px;
    .table {
        width: calc(100% - 100px);
    }
}
/deep/ .el-select {
    width: 100%;
}

/deep/ .el-select__tags {
    flex-wrap: nowrap;

    .el-tag.el-tag--info {
        display: flex;
        align-items: center;

        .el-select__tags-text {
            display: block;
            font-size: 12px;
            max-width: 80px;
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
        }
    }
}
</style>
